<template>
    <el-container class="layout-container-demo" style="height: 100%">
      <el-container>
        <el-main>
          <div class="p-header" >
            <el-form label-width="70px" ref="queryRef" :inline="true" size="large">
              <el-form-item label="视频id">
                <el-input v-model="queryParams.vid" placeholder="请输入视频id" clearable @keyup.enter="handleQuery"/>
              </el-form-item>
              <el-form-item label="视频标题">
                <el-input v-model="queryParams.vTitle" placeholder="请输入视频标题" clearable @keyup.enter="handleQuery"/>
              </el-form-item>
              <el-form-item label="视频类型">
                <el-select v-model="queryParams.classify" placeholder="请选择视频类型" style="width: 240px" clearable @keyup.enter="handleQuery">
                  <el-option
                      v-for="item in options"
                      :key="item.value"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button @click="handleQuery">搜索</el-button>
                <el-button @click="resetQuery">重置</el-button>
                <el-button type="primary" plain @click="handleAdd">新增影片</el-button>
              </el-form-item>
            </el-form>
          </div>
          <el-scrollbar>
            <el-table :data="movieData" height="800px">
              <el-table-column prop="vid" label="ID" width="120" />
              <el-table-column prop="vtitle" label="标题" width="150" />
              <el-table-column prop="vimg" label="封面" width="120">
                <template v-slot="scope">
                  <el-image :src="scope.row.vimg"></el-image>
                </template>
              </el-table-column>
              <el-table-column prop="score" label="评分" width="120"/>
              <el-table-column prop="classify" label="类别" width="140" />
              <el-table-column prop="protagonist" label="主演" width="120" />
              <el-table-column prop="description" label="描述" />
              <el-table-column prop="vurl" label="播放链接" width="140">
                <template v-slot="scope">
                  <el-link :href="scope.row.vurl" type="primary">点击跳转播放</el-link>
                </template>
              </el-table-column>
              <el-table-column  label="操作" width="240">
                <template v-slot="scope">
                  <el-button type="primary" plain @click="handleUpdate(scope.row)">修改</el-button>
                  <el-button type="primary" plain @click="handleDelete(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-scrollbar>
        </el-main>
      </el-container>
    </el-container>
  <!-- 添加或修改影视对话框 -->
  <el-dialog :title="title" :model-value="open" width="500px" append-to-body :show-close="false">
    <el-form :model="form"  label-width="80px">
      <el-form-item label="影视标题" prop="vtitle">
        <el-input v-model="form.vtitle" placeholder="请输入影视标题" />
      </el-form-item>
      <el-form-item label="评分" prop="score">
        <el-input v-model="form.score" placeholder="请输入评分" />
      </el-form-item>
      <el-form-item label="分类" prop="classify">
        <el-select v-model="form.classify" placeholder="请选择分类">
          <el-option
              v-for="item in movieType"
              :key="item.value"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="主演" prop="protagonist">
        <el-input v-model="form.protagonist" placeholder="请输入主演" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
      </el-form-item>
      <el-form-item label="播放链接" prop="vurl">
        <el-input v-model="form.vurl" placeholder="请输入播放链接" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script setup>

import {onMounted, ref} from "vue";
import {addMovie, delMovie, getMovieList, updateMovie} from "@/api/movie.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {Plus} from "@element-plus/icons-vue";
const options = [
  {
    value: '电视剧',
  },
  {
    value: '电影',
  },
  {
    value: '动漫',
  },
  {
    value: '综艺',
  }
]
const movieType = [
  {
    value: '电视剧',
  },
  {
    value: '电影',
  },
  {
    value: '动漫',
  },
  {
    value: '综艺',
  }
]
const open = ref(false)
const img = 'https://m.360buyimg.com/babel/jfs/t1/10038/12/16980/41734/628f7e76Ee902fcae/a12f81786f1b4692.jpg'
const movieData = ref([{
  vid:'',
  vtitle:'',
  score:'',
  vimg:'',
  classify:'',
  protagonist:'',
  description:'',
  vurl:'',
}])
const queryParams = ref({
  vid:'',
  vTitle:'',
  classify:''
})
const title = ref('')
onMounted( () => {
    getList();
})
// 表单参数
const form = ref({
  vid: '',
  vTitle:'',
  vimg:'',
  score:'',
  classify:'',
  protagonist:'',
  description:'',

  vurl:'',
})
//搜索
function handleQuery(){
  getMovieList(queryParams.value).then( (res) => {
    movieData.value = res.data.data


  })
}
//搜索重置
function resetQuery(){
  queryParams.value = {
    vid: null,
    vTitle: null,
    classify:null
  };
  getList()
}
//表单重置
function resetForm(){
  form.value = {
    vid:null,
    vtitle:null,
    vimg:null,
    score:null,
    classify:null,
    protagonist:null,
    description:null,
    vurl:null
  }
}
//获取影视列表
function getList(){
  getMovieList().then( (res)=>{
    movieData.value = res.data.data
  })
}
//新增弹窗
function handleAdd() {
  resetForm();
  open.value = true;
  title.value = "添加影视";
  console.log(open.value)
}

function handleUpdate(row) {
  resetForm();
  const vid = {vid:row.vid};
  form.value.vid = row.vid
  getMovieList(vid).then((response) => {
    form.value = response.data.data[0];
    console.log("form.value",form.value)
    console.log("response.data.data",response.data.data)
    open.value = true;
    title.value = "修改影视";
  });
}
//提交表单
function submitForm() {
      if (form.value.vid != null) {
        updateMovie(form.value).then((response) => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        });
      }else{
        form.value.vimg = img;
        console.log(form.value)
        addMovie(form.value).then((response) => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        });
      }
}
//删除
function handleDelete(row) {
  const vids = row.vid;
  ElMessageBox.alert('是否确认删除影视编号为"' + vids + '"的数据项？').then(() => {
    return delMovie(vids);
  }).then(() => {
    getList();
    ElMessage.success("删除成功");
  }).catch(() => {});
}
// 取消按钮
function cancel() {
  open.value = false;
  resetForm();
}
function beforeUpload(file) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isJpgOrPng) {
    ElMessage.error('上传文件必须是 JPG 或 PNG 格式');
  }
  if (!isLt2M) {
    ElMessage.error('上传文件大小不能超过 2MB');
  }
  return isJpgOrPng && isLt2M;
}
function getBase64(blob) {
  return new Promise(function (resolve, reject) {
    let reader = new FileReader();
    let imgResult = "";

    reader.onload = function () {
      imgResult = reader.result;
    };

    reader.onerror = function (error) {
      reject(error);
    };

    reader.onloadend = function () {
      resolve(imgResult);
    };

    const img = new Image();
    img.src = URL.createObjectURL(blob);

    img.onload = function () {
      let width = img.width;
      let height = img.height;

      if (width > 500 || height > 500) {
        const ratio = Math.min(500 / width, 500 / height);
        width *= ratio;
        height *= ratio;
      }

      const canvas = document.createElement('canvas');
      canvas.width = width;
      canvas.height = height;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0, width, height);

      canvas.toBlob((newBlob) => {
        if (newBlob) {
          reader.readAsDataURL(newBlob);
        } else {
          reader.readAsDataURL(blob);
        }
      }, 'image/jpeg', 0.6);
    };

    img.onerror = function (err) {
      reader.readAsDataURL(blob);
    };

  });
}

function handleChange(file) {
  getBase64(file.raw).then(img => {
    movieData.value.vimg = img;
  })
}
</script>

<style scoped>

</style>
